package com.cjhme.common.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cjhme.common.constant.CommonConstants;

public class JWTUtil {

	/**
	 * 创建token
	 * 
	 * @param key
	 * @param value
	 * @param signKey
	 * @param expiresHour
	 * @return
	 */
	public static String createToken(String withClaimKey, String withClaimVal, Integer expiresHour) {
		String signKey = ConfigUtil.getInstance().getPopString(CommonConstants.REQUEST_AES_KEY);
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.HOUR_OF_DAY, null == expiresHour ? 24 : expiresHour);
		// 过期时间
		Date expiresDate = nowTime.getTime();
		Map<String, Object> map = new HashMap<String, Object>();
		// 声明类型和方法
		map.put("typ", "JWT");
		map.put("alg", "HS256");
		String token = JWT.create().withHeader(map).withClaim(withClaimKey, withClaimVal).withExpiresAt(expiresDate)
				.withIssuedAt(new Date()).sign(Algorithm.HMAC256(signKey));

		return token;
	}

	/**
	 * 创建用户token
	 * 
	 * @param userVal
	 * @param signKey
	 * @param expiresHour
	 * @return
	 */
	public static String createToken(String userVal) {
		String token  =  JWTUtil.createToken("userId", userVal, 24);
		return AesUtil.base64Encode(token.getBytes());
	}

	/**
	 * 验证token
	 * 
	 * @param token
	 * @param signKey
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Claim> verifyToken(boolean baseConvert,String token) throws Exception {
		String signKey = ConfigUtil.getInstance().getPopString(CommonConstants.REQUEST_AES_KEY);
		String tokenStr = baseConvert?new String(AesUtil.base64Decode(token)):token;
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(signKey)).build();
		DecodedJWT jwt = verifier.verify(tokenStr);
		return jwt.getClaims();

	}

	public static void main(String[] args) {
		try {
			String token = JWTUtil.createToken("123456");
			Map<String, Claim> map = JWTUtil.verifyToken(true,token);
			System.out.println(token);
			System.out.println(map.get("userId").asString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
